// pages/settleIn/index.js
import { areaList } from '../../miniprogram_npm/@vant/area-data/data';
const util = require('../../utils/util.js')
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    areaList,
    typeList:[],
    province:'',
    city:'',
    area:'',
    typeId:'',
    image:'',
    idHead:'',
    idEmblem:'',
    businessLicense:'',
    storeImage:'',
    typeIndex:-1,
    isClick:false
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
   
    this.typeList()
  },
  typeList(){
    app.agriknow.getClickList().then(res=>{
 
      this.setData({
        typeList:res.data,
 
      })
    })
  },
  submit(){
    wx.showLoading({
      title: '提交中',
      mask:true
    })
    if(!this.data.name) return this.tip('请输入店铺名称');
    if(!this.data.typeId) return this.tip('请选择店铺分类');
    if(!this.data.area) return this.tip('请选择店铺地址');
    if(!this.data.address) return this.tip('请输入详细地址');
    if(!this.data.userName) return this.tip('请输入店主姓名');
    if(!this.data.mobile) return this.tip('请输入联系方式');
    if(this.data.image=='../../static/settleIn/tx.png') return this.tip('请上传店铺头像');
    if(this.data.storeImage=='../../static/settleIn/zp.png') return this.tip('请上传店铺照片');
    if(this.data.idHead=='../../static/settleIn/rx.png') return this.tip('请上传人像面');
    if(this.data.idEmblem=='../../static/settleIn/gh.png') return this.tip('请上传国徽面');
    // if(this.data.businessLicense=='../../static/settleIn/yyzz.png') return this.tip('请上传营业执照');
    let data = {
      name:this.data.name,
      typeId:this.data.typeId,
      province:this.data.province,
      city:this.data.city,
      area:this.data.area,
      address:this.data.address,
      userName:this.data.userName,
      mobile:this.data.mobile,
      image:this.data.image,
      idHead:this.data.idHead,
      idEmblem:this.data.idEmblem,
      businessLicense:this.data.businessLicense,
      storeImage:this.data.storeImage,
      situation:wx.getStorageSync('locationInfo').location.lng,
      latitude:wx.getStorageSync('locationInfo').location.lat
    }
    var isClick=this.data.isClick
   
    if(isClick){
      return false
    }else{
      this.setData({
        isClick:true
      })
    }
    setTimeout(function(){
      this.setData({
        isClick:false
      })
    },1500)
    app.agriknow.userApplyStore(data).then(res=>{
      console.log(res)
      wx.hideLoading()
      if(res.code=='000000'){
        wx.showModal({
          title: '提示',
          content: '提交成功',
          showCancel:false,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          }
        })
      }
    }).catch(res=>{
      wx.hideLoading()
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000,
        mask: true
      })
    })
  },
  upload(e) {
    let index = e.currentTarget.dataset.index
    let that = this
    wx.chooseMedia({
      count:1,
      success (res) {
        console.log(res.tempFiles[0].tempFilePath)
        const tempFilePaths = res.tempFiles[0].tempFilePath
        wx.uploadFile({
          url: app.agriknow._baseUrl+'ht/user/uploadImage', //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            console.log(res)
            if(index==1){
              that.setData({
                storeImage:JSON.parse(res.data).data
              })
            }else if(index==2){
              that.setData({
                idHead:JSON.parse(res.data).data
              })
            }else if(index==3){
              that.setData({
                idEmblem:JSON.parse(res.data).data
              })
            }else if(index==4){
              that.setData({
                businessLicense:JSON.parse(res.data).data
              })
            }else if(index==5){
              that.setData({
                image:JSON.parse(res.data).data
              })
            }
            
          }
        })
      }
    })
  },
  bindCancel(e){
    this.setData({
      isAddress:false
    })
  },
  bindConfirm(e){
    let address = e.detail.values[0].name + ',' + e.detail.values[1].name + ',' + e.detail.values[2].name
    this.setData({
      isAddress:false,
      region:address,
      province:e.detail.values[0].name,
      city:e.detail.values[1].name,
      area:e.detail.values[2].name
    })
  },
  onChange(event) {
    const { picker, value, index } = event.detail;
    Toast(`当前值：${value}, 当前索引：${index}`);
  },
  onCancel(e){
    console.log(e)
    this.setData({
      isPopup:false
    })
  },
  onConfirm(e){
    console.log('1',e.detail.index)
    this.setData({
      isPopup:false,
      type:e.detail.value,
      typeId:this.data.typeList[e.detail.index].id
    })
  },
  openPopup(){
    this.setData({
      isPopup:true
    })
  },
  openAddress(){
    this.setData({
      isAddress:true
    })
  },
  tip(name){
    wx.showToast({
      title: name,
      icon:'none',
      duration: 2000
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  chooseLocation:function(e){
      let that = this
      wx.getSetting({
        success(res) {
          console.log('res是否开启授权', res)
          if (!res.authSetting['scope.userLocation']) { 
            wx.authorize({
              scope: 'scope.userLocation',  
              success() {
                // console.log('前用户发起授权请求')
                wx.chooseLocation({
                  success: res => {
                    that.getValueMap(res)
                  },
                  fail: res => {
                    console.log('打开地图选择位置取消', res)
                  }
                })
              },
              fail() {
                // 用户点击不允许引导重新获取授权
                that.fetchAgainLocation()
              }
            })
          } else {
              // 已经授权了就会直接进入地图
            wx.chooseLocation({
              success: res => {
                that.getValueMap(res)
              },
              fail: res => {
              console.log('打开地图选择位置取消', res)
              }
            })
          }
        }
      })
    },

    fetchAgainLocation() {
      let that = this
      wx.getSetting({
        success: (res) => {
          console.log(res)
          var statu = res.authSetting;
          if (!statu['scope.userLocation']) {
            wx.showModal({
              title: '是否授权当前位置',
              content: '需要获取您的地理位置，请确认授权，否则地图功能将无法使用',
              success: (tip) => {
                if (tip.confirm) {
                  wx.openSetting({
                    success: (data) => {
                      if (data.authSetting["scope.userLocation"] === true) {
                        wx.showToast({
                          title: '授权成功',
                          icon: 'success',
                          duration: 1000
                        })
                        wx.chooseLocation({
                          success: res => {
                            that.getValueMap(res)
                          }
                        })
                      } else {
                        wx.showToast({
                          title: '授权失败',
                          icon: 'success',
                          duration: 1000
                        })
                      }
                    },
                    fail: () => {},
                    complete: () => {}
                  });
                }
              }
            })
          }
        },
        fail: ()=>{},
        complete: ()=>{}
      })
    },
    // 地图共用赋值
  getValueMap(res){
    let that = this
    console.log(res)
    that.setData({
    
      location:{
        address:res.address,
        name:res.name,
        longitude: res.longitude,
        latitude: res.latitude,
      },
      markers: [{
        id: 0,
        latitude: res.latitude,
        longitude: res.longitude,
        title: res.name,
        iconPath: '/static/settleIn/location_icon.png', // 标记点的图标
        width: 30,
        height: 30
      }]
    })
    var locationVal=res.latitude+','+res.longitude
    util.chooseLocationData(locationVal)
  },

  choosePoi:function(e){
    let that = this
    wx.getSetting({
      success(res) {
        console.log('res是否开启授权', res)
        if (!res.authSetting['scope.userLocation']) { 
          wx.authorize({
            scope: 'scope.userLocation',  
            success() {
              // console.log('前用户发起授权请求')
              wx.choosePoi({
                success: res => {
                  console.log('choosePoi',res)
                },
                fail: res => {
                  console.log('打开地图选择位置取消', res)
                }
              })
            },
            fail() {
              // 用户点击不允许引导重新获取授权
              that.fetchAgainLocation()
            }
          })
        } else {
            // 已经授权了就会直接进入地图
          wx.choosePoi({
            success: res => {
             console.log(res)
            },
            fail: res => {
            console.log('打开地图选择位置取消', res)
            }
          })
        }
      }
    })
  },

  pickerChange:function(e){
    var val=e.detail.value
    if(val==-1){
      return false
    }
    var name=e.currentTarget.dataset.name
    var key=name+'Index'
    this.setData({
        [key]:val
    })
  },

  uploadImg(e) {
    let key = e.currentTarget.dataset.name
    let that = this
    wx.chooseMedia({
      count:1,
      success (res) {
        console.log(res.tempFiles[0].tempFilePath)
        const tempFilePaths = res.tempFiles[0].tempFilePath
        wx.uploadFile({
          url: app.agriknow._baseUrl+'ht/user/uploadImage', //仅为示例，非真实的接口地址
          filePath: tempFilePaths,
          name: 'file',
          formData: {
            'user': 'test'
          },
          success (res){
            that.setData({
              [key]:JSON.parse(res.data).data
            })
            
          }
        })
      }
    })
  },
  formSubmit(e){
   
    var that=this
    var data=e.detail.value
    var typeIndex=this.data.typeIndex
    var location=this.data.location
    var mobileReg=/^1[3-9]\d{9}$/
    var nameReg=/^[\u4e00-\u9fa5\s]{2,10}$/
    var tips=''
    var locationInfo= wx.getStorageSync('locationInfo')
    /*
    if(!locationInfo){
      location={}
      locationInfo={
        address_component:{
          province:'广东省',
          city:'惠州市',
          district:'惠城区'
        },
        location:{
          lng:114.407763,
          lat:23.064389
        }
      }
    }
    */
      data.typeId=this.data.typeList[typeIndex].id
      data.province=locationInfo.address_component.province
      data.city=locationInfo.address_component.city
      data.area=locationInfo.address_component.district
      data.image=this.data.image
      data.idHead=this.data.idHead
      data.idEmblem=this.data.idEmblem
      data.businessLicense=this.data.businessLicense
      data.storeImage=this.data.storeImage
      data.situation=locationInfo.location.lng
      data.latitude=locationInfo.location.lat
    if(!data.name){
      tips='请输入店铺名称'
    }else if(typeIndex==-1){
      tips='请选择店铺分类'
    }else if(!location){
      tips='请选择店铺位置'
    }else if(!data.address){
      tips='请输入详细地址'
    }else if(!data.userName){
      tips='请输入店主姓名'
    }else if(data.userName && !nameReg.test(data.userName)){
      tips='请输入正确的店主姓名'
    }else if(!data.mobile){
      tips='请输入手机号码'
    }else if(data.mobile && !mobileReg.test(data.mobile)){
      tips='请输入正确的手机号码'
    }else if(!data.describe){
      tips='请输入店铺描述'
    }else if(!data.image){
      tips='请上传店铺头像'
    }else if(!data.storeImage){
      tips='请上传店铺照片'
    }else if(!data.idHead){
      tips='请上传人像面'
    }else if(!data.idEmblem){
      tips='请上传国徽面'
    }

    if(tips){
      wx.showToast({
        title: tips,
        icon:'none',
        duration:2000,
        mask:true
      })
      return false
    }
    wx.showLoading({
      title: '提交中',
      mask:true
    })
    

    app.agriknow.userApplyStore(data).then(res=>{
      console.log(res)
      wx.hideLoading()
      if(res.code=='000000'){
        wx.showModal({
          title: '提示',
          content: '提交成功',
          showCancel:false,
          success (res) {
            if (res.confirm) {
              console.log('用户点击确定')
              wx.navigateTo({
                url: '/pages/login/index',
              })
            }
          }
        })
      }
    }).catch(res=>{
      wx.hideLoading()
      wx.showToast({
        title: res.message,
        icon: 'none',
        duration: 2000,
        mask: true
      })
    })
  },
  
  
})